<template>
  <view class="container">
    <view class="header">
      <text class="title">身份认证</text>
      <text class="subtitle">请完善您的身份信息</text>
    </view>

    <view class="form">
      <view class="form-item">
        <text class="label">学/工号</text>
        <input class="input" v-model="account" placeholder="请输入学号或工号" placeholder-class="placeholder" maxlength="20" />
      </view>

      <view class="form-item">
        <text class="label">手机号</text>
        <input class="input" v-model="phone" placeholder="请输入手机号" placeholder-class="placeholder" type="number"
          maxlength="11" />
      </view>

      <view class="form-item">
        <text class="label">输入密码</text>
        <input class="input" v-model="password" password placeholder="请输入您的密码" placeholder-class="placeholder"
          maxlength="20" />
      </view>

      <view class="form-item">
        <text class="label">身份</text>
        <picker class="picker" mode="selector" :range="roleOptions" range-key="label" @change="onRoleChange">
          <view class="picker-content">
            {{ selectedRole.label }}
            <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
          </view>
        </picker>
      </view>

      <button class="submit-btn" :disabled="!formValid" @click="handleSubmit">完成认证</button>
    </view>
  </view>
</template>

<script>
  import {
    ajax
  } from "../../utils/request.js";
  import {
    loginFn,
    getPhoneNumberFn
  } from "../../pages/person/login.js"
  export default {
    data() {
      return {
        account: '',
        phone: '',
        password: '',
        selectedRole: {
          label: '学生',
          value: 'student'
        },
        roleOptions: [{
            label: '学生',
            value: 'student'
          },
          {
            label: '老师',
            value: 'teacher'
          }
        ]
      }
    },
    computed: {
      formValid() {
        return (
          this.account &&
          this.phone &&
          this.password &&
          /^1[3-9]\d{9}$/.test(this.phone)
        )
      }
    },
    methods: {
      updateUserRole() {
        try {
          this.userRole = uni.getStorageSync('role') || '';
          console.log('当前用户角色:', this.userRole);
        } catch (e) {
          console.error('获取角色失败:', e);
          this.userRole = '';
        }
      },
      onRoleChange(e) {
        this.selectedRole = this.roleOptions[e.detail.value]
      },
      handleSubmit() {
        if (!this.account) {
          uni.showToast({
            title: '请输入学/工号',
            icon: 'none'
          })
          return
        }

        if (!/^1[3-9]\d{9}$/.test(this.phone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return
        }

        if (!this.password) {
          uni.showToast({
            title: '请输入密码',
            icon: 'none'
          })
          return
        }

        // 调用身份认证接口
        this.submitAuth({
          account: this.account,
          phone: this.phone,
          password: this.password,
          role: this.selectedRole.value
        })
      },
      async submitAuth(params) {
        uni.showLoading({
          title: '提交中...'
        })

        try {
          const res = await ajax('/api/user/studentauthuserinfo', 'POST', params);
                  uni.setStorageSync('userInfo', res.data.userinfo);
    uni.setStorageSync('token', res.data.token);
          if (!res.success) {
            throw new Error(res.msg || '认证失败');
          }
          uni.hideLoading()

          uni.showToast({
            title: '认证成功!',
            icon: 'none'
          })
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/person/person"
            })

          }, 1500)
          loginFn().then(openIdRes => {
            const phoneCode = uni.getStorageSync('phoneCode')
            console.log(phoneCode, 222);
            console.log(openIdRes, 333);
            getPhoneNumberFn(phoneCode, openIdRes).then(loginRes => {
              console.log(loginRes, 111);
              if (loginRes.success) {


                uni.setStorageSync('token', loginRes.data.token);

                uni.setStorageSync('role', loginRes.data.userinfo.role || ''); // 存储角色
                this.updateUserRole(); // 登录后立即更新角色

              }
            });
          });

          console.log('认证参数:', params)
        } catch (error) {
          uni.hideLoading()
          uni.showToast({
            title: error.message || '认证失败',
            icon: 'none'
          })
          console.error('认证错误:', error)
        }
      }
    }
  }
</script>

<style>
  .container {
    padding: 40rpx;
    display: flex;
    flex-direction: column;
  }

  .header {
    margin-top: 60rpx;
    margin-bottom: 80rpx;
  }

  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: #2ba245;
    display: block;
    margin-bottom: 16rpx;
  }

  .subtitle {
    font-size: 28rpx;
    color: #999;
  }

  .form {
    width: 100%;
  }

  .form-item {
    margin-bottom: 40rpx;
  }

  .label {
    font-size: 16px;
    color: #333;
    display: block;
    margin-bottom: 20rpx;
  }

  .input {
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 16px;
  }

  .placeholder {
    color: #999;
    font-size: 16px;
  }

  .picker {
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
  }

  .picker-content {
    height: 100%;
    line-height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20rpx;
    font-size: 16px;
    color: #333;
  }

  .submit-btn {
    margin-top: 80rpx;
    background-color: #2ba245;
    color: white;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 16px;
  }

  .submit-btn[disabled] {
    background-color: #cccccc;
    color: #000;
  }

  .submit-btn:active:not([disabled]) {
    opacity: 0.8;
  }
</style>